//
//  YCAlertView3.m
//  CustomByWindow
//
//  Created by tangkexiong on 16/2/15.
//  Copyright © 2016年 tangkexiong. All rights reserved.
//

#import "YCAlertView3.h"

#define kDlgWidth 270.f
#define kBtnHeight 44.f
#define kTitleHeight 39.f
#define kBtnMaxHeight (kBtnHeight*4)
#define kTitleFont 17.f
#define kMessageFont 15.f
#define kAnimationDuration 0.3f
#define kViewAlpha 0.9f

#pragma mark - YCAlertView3Cell

@implementation YCAlertView3Cell

@end

#pragma mark - YCAlertView3

@interface YCAlertView3()<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout> {
    UIWindow *_window;
    UIWindow *_oldWindow;
}

@property (nonatomic, retain) UIImage *cancelImg;
@property (nonatomic, copy) NSString *message;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, strong) NSMutableArray *btnTitleArray;

@end

@implementation YCAlertView3

@synthesize title = _title;
@synthesize message = _message;
@synthesize cancelImg = _cancelImg;
@synthesize btnTitleArray = _btnTitleArray;

#pragma mark - UIViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self _configView];
}

- (void)_configView {
    self.view.backgroundColor = [UIColor clearColor];
    
    _bgView.backgroundColor = [UIColor blackColor];
    [_bgView.superview sendSubviewToBack:_bgView];
    _bgView.alpha = 0.5f;
    
    _alertView.layer.cornerRadius = 5.f;
    _alertView.backgroundColor = [UIColor colorWithRed:219/255.f green:219/255.f blue:219/255.f alpha:1.0];
    _alertView.clipsToBounds = YES;
    
    [_myCollectionView registerNib:[UINib nibWithNibName:@"YCAlertView3Cell" bundle:nil] forCellWithReuseIdentifier:@"cellAction"];
    _myCollectionView.dataSource = self;
    _myCollectionView.delegate = self;
    
    // 设置内容
    _titleLabel.text = _title;
    _contentLabel.text = _message;
    _contentLabel.numberOfLines = 0;
    [_cancelBtn setImage:_cancelImg forState:UIControlStateNormal];
    // 配置约束
    if (_title || _cancelImg) {
        _constraintTitleViewHeight.constant = kTitleHeight;
    } else {
        _constraintTitleViewHeight.constant = 0.f;
    }
    if (_btnTitleArray.count > 0) {
        _constraintBtnViewHeight.constant = kBtnHeight;
    } else {
        _constraintBtnViewHeight.constant = 0.f;
    }
    CGFloat heightContent = [self _heightOfStr:_message strFont:_contentLabel.font maxWidth:kDlgWidth] + 8.f;
    heightContent = heightContent<36.f ? 36.f : heightContent;
    _constraintAlertViewHeight.constant = _constraintBtnViewHeight.constant + _constraintTitleViewHeight.constant + heightContent;
    // 更新视图
    [self.view setNeedsDisplay];
}

#pragma mark - UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _btnTitleArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YCAlertView3Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellAction" forIndexPath:indexPath];
    
    cell.label.text = _btnTitleArray[indexPath.row];
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (_btnTitleArray.count > 2) {
        return CGSizeMake(kDlgWidth, kBtnHeight);
    } else if (_btnTitleArray.count > 1) {
        return CGSizeMake((kDlgWidth-0.5f)/2, kBtnHeight);
    } else {
        return CGSizeMake(kDlgWidth, kBtnHeight);
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0.5f, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0.5;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0.5;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([_myDelegate respondsToSelector:@selector(alertView3:didClickedAtIndex:)]) {
        [_myDelegate alertView3:self didClickedAtIndex:indexPath.row];
    }
    
    [self _dismiss];
}

#pragma mark - IBAction

- (IBAction)cancelBtnClicked:(id)sender {
    if ([_myDelegate respondsToSelector:@selector(alertView3DidCancel:)]) {
        [_myDelegate alertView3DidCancel:self
         ];
    }
    
    [self _dismiss];
}

#pragma mark - Control

- (void)_showAnimation {
    [UIView animateWithDuration:kAnimationDuration animations:^{
        _bgView.alpha = 0.5;
    } completion:^(BOOL finished) {
        
    }];
    
    CAKeyframeAnimation *popAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    popAnimation.duration = kAnimationDuration;
    popAnimation.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.01f, 0.01f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1f, 1.1f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9f, 0.9f, 0.9f)],
                            [NSValue valueWithCATransform3D:CATransform3DIdentity]];
    popAnimation.keyTimes = @[@0.2f, @0.5f, @0.75f, @1.0f];
    popAnimation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [_alertView.layer addAnimation:popAnimation forKey:nil];
}

- (void)_dismiss {
    [self _dismissAnimation];
}

- (void)_dismissAnimation {
    [UIView animateWithDuration:kAnimationDuration animations:^{
        _bgView.alpha = 0.0;
        _alertView.alpha = 0.0;
    } completion:^(BOOL finished) {
        [_window resignKeyWindow];
        [_oldWindow resignKeyWindow];
        
        _window = nil;
    }];
}

#pragma mark - Other

- (CGFloat)_heightOfStr:(NSString *)str strFont:(UIFont *)font maxWidth:(CGFloat)width {
    if (str.length == 0) {
        return 0;
    }
    NSDictionary *attrs = @{NSFontAttributeName:font};
    return  [str boundingRectWithSize:CGSizeMake(width, 0)
                              options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                           attributes:attrs
                              context:nil].size.height;
}

#pragma mark - Public

+ (instancetype)instanceWithTitle:(NSString *)title message:(NSString *)message cancelBtnImg:(UIImage *)image delegate:(id<YCAlertView3Delegate>)delegate buttonTitles:(NSString *)btnTitle, ... {
    YCAlertView3 *alert = [[YCAlertView3 alloc] initWithNibName:@"YCAlertView3" bundle:nil];
    // 保存信息
    alert.title = title;
    alert.cancelImg = image;
    alert.message = message;
    alert.myDelegate = delegate;
    alert.btnTitleArray = [[NSMutableArray alloc] init];
    va_list args;
    va_start(args, btnTitle);
    if (btnTitle) {
        [alert.btnTitleArray addObject:btnTitle];
        while ((btnTitle=va_arg(args, NSString *))) {
            [alert.btnTitleArray addObject:btnTitle];
        }
    }
    va_end(args);
    
    
    return alert;
}

- (void)show {
    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _window.windowLevel = 440.f;
    _window.rootViewController = self;
    _oldWindow = [UIApplication sharedApplication].keyWindow;
    [_window makeKeyAndVisible];
    
    [self _showAnimation];
}

@end
